
//
//  LMAccountTool.m
//  李明微博
//
//  Created by 张青花 on 15/12/9.
//  Copyright (c) 2015年 李明. All rights reserved.
//

#import "LMAccountTool.h"
#import "LMAccount.h"
#import "LMHttpTool.h"
#import "LMAccountParam.h"
#import "MJExtension.h"

#define LMAccountFileName [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"account.data"]

#define  APPKEY @"3671842877"
#define  AppSecret @"f38d6f18a8b1632621d564a1b644a61a"
#define  OAuthURl @"https://api.weibo.com/"

@implementation LMAccountTool

static LMAccount *_account;
+ (void)saveAccount:(LMAccount *)account
{
    [NSKeyedArchiver archiveRootObject:account toFile:LMAccountFileName] ;
}

+ (LMAccount *)account
{
    if (_account ==nil) {
        _account = [NSKeyedUnarchiver unarchiveObjectWithFile:LMAccountFileName];
        
        if ([[NSDate date] compare:_account.expires_date]!=NSOrderedAscending) {
            _account = nil;
        }
    }
    return _account;

}


+ (void)accessTokenWithCode:(NSString *)code success:(void (^)())success failure:(void (^)(NSError *))failure
{
    LMAccountParam *parameter = [[LMAccountParam alloc] init];
    
    parameter.client_id =APPKEY;
    parameter.client_secret =AppSecret;
    parameter.grant_type =@"authorization_code";
    parameter.code =code;
    parameter.redirect_uri =@"http://www.baidu.com";
    
    [LMHttpTool POST:@"https://api.weibo.com/oauth2/access_token" parameters:parameter.mj_keyValues success:^(id responseObject) {
        
        LMAccount *account = [LMAccount initWithAccount:responseObject];
        
        [LMAccountTool saveAccount:account];
        
        if (success) {
            success();
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
        if (failure) {
            failure(error);
        }
    }];
    
}

@end
